package com.github.tvbox.osc.player.controller;

import android.animation.Animator;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.transition.TransitionManager;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewAnimationUtils;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.github.tvbox.osc.R;
import com.github.tvbox.osc.player.thirdparty.MXPlayer;
import com.github.tvbox.osc.player.thirdparty.ReexPlayer;
import com.github.tvbox.osc.ui.adapter.ParseAdapter;
import com.github.tvbox.osc.ui.adapter.SelectDialogAdapter;
import com.github.tvbox.osc.ui.dialog.SelectDialog;
import com.github.tvbox.osc.util.FastClickCheckUtil;
import com.github.tvbox.osc.util.HawkConfig;
import com.github.tvbox.osc.util.PlayerHelper;
import com.orhanobut.hawk.Hawk;
import com.orhanobut.logger.Logger;
import com.owen.tvrecyclerview.widget.V7LinearLayoutManager;

import org.jetbrains.annotations.NotNull;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.RecyclerView;
import xyz.doikki.videoplayer.player.VideoView;
import xyz.doikki.videoplayer.util.PlayerUtils;

import static xyz.doikki.videoplayer.util.PlayerUtils.stringForTime;

/**
 * 播放控制器(is android View)设计上要独立一点，减少对第三方依赖。(自定义，可以放宽)
 */
public class VodController extends BaseController {
    private static final String TAG = "APP.Vod.";

    public VodController(@NonNull Context context) {
        super(context);
        mHandlerCallback = new HandlerCallback() {
            @Override
            public void callback(Message msg) {
                switch (msg.what) {
                    case 1000: { // seek 刷新
                        handleShowProgress();
                        break;
                    }
                    case 1001: { // seek 关闭
                        handleHideProgress();
                        break;
                    }
                    case 1002: { // 显示底部菜单
                        handleShowBottomMenu();
                        break;
                    }
                    case 1003: { // 隐藏底部菜单
                        handleHideBottomMenu();
                        break;
                    }
                    case 1004: { // 设置速度
                        handlePlaySpeed();
                        break;
                    }
                }
            }
        };
    }

    @Override
    protected int getLayoutId() {
        return R.layout.player_vod_control_view;
    }

    /**
     * 控制器回听器
     */
    public interface VodControlListener {
        /**
         * 播放下一个
         */
        void playNext(boolean rmProgress);

        /**
         * 播放上一个
         */
        void playPrev();

        void updatePlayerCfg();

        void replay();

        void errReplay();
    }

    private void handlePlaySpeed() {
        if (isInPlaybackState()) {
            setSpeed(1.0F);
        } else mHandler.sendEmptyMessageDelayed(1004, 100);
    }

    private void handleShowProgress() {
        mProgressRoot.setVisibility(VISIBLE);
        if (isPaused) {
            mProgressTop.setVisibility(GONE);
        }
    }

    private void handleHideProgress() {
        mProgressRoot.setVisibility(GONE);
        if (isPaused) {
            mProgressTop.setVisibility(VISIBLE);
        }
    }

    private void handleHideBottomMenu() {
        mBack.setVisibility(GONE);
        mLockView.setVisibility(GONE);
        VodAnim.animateViewVisibility(mTopRoot, View.GONE, -mTopRoot.getHeight() >> 1, 0.0f, false);
        VodAnim.animateViewVisibility(mBottomRoot, View.GONE, mBottomRoot.getHeight() >> 1, 0.0f, false);

    }

    private void handleShowBottomMenu() {
        mBack.setVisibility(VISIBLE);
        showLockView();

        if (isKeyUp) {
            mPlayerTimeStartBtn.requestFocus();
            isKeyUp = false;
        } else {
            mPauseBtn.requestFocus();
        }


        VodAnim.animateViewVisibility(mTopRoot, VISIBLE, -mTopRoot.getHeight() >> 1, 1.0f, true);
        VodAnim.animateViewVisibility(mBottomRoot, VISIBLE, mBottomRoot.getHeight() >> 1, 1.0f, true);

        mHandler.postDelayed(mUpdateLayout, 255); // 已知的Workaround Fix: SurfaceView
    }

    SeekBar mSeekBar;
    TextView mCurrentTime;
    TextView mTotalTime;
    boolean mIsDragging;
    View mProgressRoot;
    TextView mProgressText;
    ImageView mProgressIcon;
    View mBottomRoot;
    View mParseRoot;
    RecyclerView mGridView;
    TextView mPlayTitle;
    View mNextBtn;
    View mPrevBtn;

    View mPlayerView;
    View mPlayerTextBtn;
    TextView mPlayerIJKBtn;
    View mPlayerRetry;
    TextView mPlayerTimeStartBtn;
    TextView mPlayerTimeSkipBtn;
    TextView mPlayerTimeStepBtn;

    View mTopHide;
    View mTopRoot;
    View mPlayerResolution;
    View mSpeedHidell;
    View mSpeedll;
    View mProgressTop;
    View mPauseIcon;
    View mTapSeek;


    // progress container
    ProgressBar mDialogVideoProgressBar;
    ProgressBar mDialogVideoPauseBar;

    // center BACK button
    LinearLayout mBack;

    ImageView mLockView;

    // screen_display
    TextView mPlayPauseTime;
    TextView mPlayLoadNetSpeedRightTop;
    /**
     * 迷你进度条
     */
    View mTopRoot2;
    TextView seekTime; //右上角进度时间显示
    View mScreenDisplay; //增加屏显开关

    // bottom container

    TextView mTime;
    TextView mTimeEnd;

    // 1. media control
    LinearLayout mPauseBtn;
    ImageView mPauseImg;


    // Fast Forward Buttons
    View mPlayerSpeedView;
    View mPlayerSpeedImg;
    View mPlayerSpeedText;

    // Scale Buttons
    View mPlayerScaleView;
    View mPlayerScaleImg;
    View mPlayerScaleTxt;

    // Player Buttons
    ImageView mPlayerImg;
    TextView mPlayerTxt;
    LinearLayout mSubtitleBtn;

    LinearLayout mAudioTrackBtn;
    public TextView mPlayerTimeResetBtn;
    public ImageView mLvPortraitBtn;
    public LinearLayout mLandscapePortraitBtn;

    // parse container
    private boolean isPaused = false;
    private boolean isKeyUp = false;

    private boolean fromLongPress;
    private float currentSpeed;
    float mSpeed;//播放速度

    @Override
    protected void initView() {
        super.initView();
        // top container
        mTopHide = findViewById(R.id.top_container_hide);
        mTopRoot = findViewById(R.id.top_container);
        mPlayTitle = findViewById(R.id.tv_title_top);
        mPlayerResolution = findViewById(R.id.tv_resolution);
        mSpeedHidell = findViewById(R.id.tv_speed_top_hide);
        mSpeedll = findViewById(R.id.tv_speed_top);

        // pause container
        mProgressTop = findViewById(R.id.tv_pause_container);
        mPauseIcon = findViewById(R.id.tv_pause_icon);
        mTapSeek = findViewById(R.id.ll_ddtap);

        mSeekBar = findViewById(R.id.seekBar);
        mProgressRoot = findViewById(R.id.tv_progress_container);
        mProgressIcon = findViewById(R.id.tv_progress_icon);
        mProgressText = findViewById(R.id.tv_progress_text);
        mBottomRoot = findViewById(R.id.bottom_container);
        mParseRoot = findViewById(R.id.parse_root);
        mGridView = findViewById(R.id.mGridView);


        // progress container
        mProgressRoot = findViewById(R.id.tv_progress_container);
        mProgressIcon = findViewById(R.id.tv_progress_icon);
        mProgressText = findViewById(R.id.tv_progress_text);
        mDialogVideoProgressBar = findViewWithTag("progressbar_video");
        mDialogVideoPauseBar = findViewWithTag("pausebar_video");

        // center back button
        mBack = findViewById(R.id.tvBackButton);

        // center lock button
        mLockView = findViewById(R.id.tv_lock);

        // bottom container
        mBottomRoot = findViewById(R.id.bottom_container);
        mTime = findViewById(R.id.tv_sys_time);
        mTimeEnd = findViewById(R.id.tv_time_end);
        mCurrentTime = findViewById(R.id.curr_time);
        mSeekBar = findViewById(R.id.seekBar);
        mTotalTime = findViewById(R.id.total_time);

        // 1. Media Control Buttons
        mPrevBtn = findViewById(R.id.play_prev);
        mPauseBtn = findViewById(R.id.play_pause);
        mPauseImg = findViewById(R.id.play_pauseImg);
        mNextBtn = findViewById(R.id.play_next);
        mPlayerRetry = findViewById(R.id.play_retry);

        // Fast Forward Buttons
        mPlayerSpeedView = findViewById(R.id.play_speed);
        mPlayerSpeedImg = findViewById(R.id.play_speed_img);
        mPlayerSpeedText = findViewById(R.id.play_speed_txt);

        // Scale Buttons
        mPlayerScaleView = findViewById(R.id.play_scale);
        mPlayerScaleImg = findViewById(R.id.play_scale_img);
        mPlayerScaleTxt = findViewById(R.id.play_scale_txt);

        // Player Buttons
        mPlayerView = findViewById(R.id.play_player);
        mPlayerImg = findViewById(R.id.play_player_img);
        mPlayerTxt = findViewById(R.id.play_player_txt);
        mPlayerIJKBtn = findViewById(R.id.play_ijk);

        mSubtitleBtn = findViewById(R.id.play_subtitle);
        mAudioTrackBtn = findViewById(R.id.play_audio);
        mPlayerTimeStartBtn = findViewById(R.id.play_time_start);
        mPlayerTimeSkipBtn = findViewById(R.id.play_time_end);
        mPlayerTimeStepBtn = findViewById(R.id.play_time_step);
        mPlayerTimeResetBtn = findViewById(R.id.play_time_reset);
        mLandscapePortraitBtn = findViewById(R.id.landscape_portrait);
        mLvPortraitBtn = findViewById(R.id.lv_portrait);

        // parse container
        mParseRoot = findViewById(R.id.parse_root);
        mGridView = findViewById(R.id.mGridView);

        // screen_display
        mPlayPauseTime = findViewById(R.id.tv_system_time);
        mPlayLoadNetSpeedRightTop = findViewById(R.id.tv_play_load_net_speed_right_top);
        mTopRoot2 = findViewById(R.id.tv_top_r_container);
        seekTime = findViewById(R.id.tv_seek_time); //右上角进度时间显示
        mScreenDisplay = findViewById(R.id.screen_display); //增加屏显开关

        mGridView.setLayoutManager(new V7LinearLayoutManager(getContext(), 0, false));
        ParseAdapter parseAdapter = new ParseAdapter();
        parseAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                hideBottom();
            }
        });
        mGridView.setAdapter(parseAdapter);

        // initialize view
        mTopRoot.setVisibility(INVISIBLE);
        mBottomRoot.setVisibility(INVISIBLE);
        mBack.setVisibility(INVISIBLE);
        mParseRoot.setVisibility(GONE);

        setupViewRootView();
        setupViewSeekBar();
        setupViewVodLock();
        setupViewBack();

        setupViewPlayPause();
        setupViewNextPlay();
        setupViewPrevPlay();
        setupViewRetryPlay();
        setupViewFFwdBtn();

        setupViewScalePlay();
        setupViewPlayerPlay();
        setupViewPlayerIJKPlay();

        setupViewTimeStartPlay();
        setupViewTimeSkipPlay();
        setupViewTimeStepPlay();
        setupViewScreenDisplay();
        setupViewSubTitle();
        setupViewAudioTrack();

        setupViewTimeResetPlay();


    }

    /**
     * --后退键按钮----------------------------------------------------------------------------
     */
    private void setupViewBack() {
        View view = mBack;
        if (view == null) {
            return;
        }
        // Button: BACK click to go back to previous page -------------------
        view.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                mTopRoot.setVisibility(GONE);
//                mBottomRoot.setVisibility(GONE);
                mBack.setVisibility(GONE);
                mLockView.setVisibility(GONE);
                mProgressTop.setVisibility(GONE);
                hideBottom();
                mHandler.removeCallbacks(mHideBottomRunnable);

                if (mActivity != null) {
                    mActivity.onBackPressed();
                }
            }
        });
    }

    private void setupViewTimeResetPlay() {
        if (mPlayerTimeResetBtn == null) {
            return;
        }
        //        增加播放页面片头片尾时间重置
        mPlayerTimeResetBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mHandler.removeCallbacks(mHideBottomRunnable);
                mHandler.postDelayed(mHideBottomRunnable, 8000);
                try {
                    mPlayerConfig.put("et", 0);
                    mPlayerConfig.put("st", 0);
                    updatePlayerCfgView();
                    mListener.updatePlayerCfg();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        mPlayerTimeResetBtn.setOnLongClickListener(new OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                try {
                    mPlayerConfig.put("st", 110);
                    mPlayerConfig.put("et", 150);
                    updatePlayerCfgView();
                    mListener.updatePlayerCfg();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
//                Toast.makeText(getContext(), "已预设片头片尾", Toast.LENGTH_SHORT).show();
                return true;
            }
        });
    }

    /**
     * --音频轨道按钮----------------------------------------------------------------------------
     */
    private void setupViewAudioTrack() {
        // Button : Audio track selection ------------------------------------
        mAudioTrackBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                FastClickCheckUtil.check(view);
//                listener.selectAudioTrack();
            }
        });
    }

    /**
     * --字幕按钮----------------------------------------------------------------------------
     */
    private void setupViewSubTitle() {
        if (mSubtitleBtn == null) {
            return;
        }
        // Button : Subtitle selection ----------------------------------------
        mSubtitleBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                FastClickCheckUtil.check(view);
//                listener.selectSubtitle();
            }
        });
        mSubtitleBtn.setOnLongClickListener(new OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
//                if (mSubtitleView.getVisibility() == View.GONE) {
//                    mSubtitleView.setVisibility(VISIBLE);
//                    hideBottom();
//                    Toast.makeText(getContext(), HomeActivity.getRes().getString(R.string.vod_sub_on), Toast.LENGTH_SHORT).show();
//                } else {
//                    mSubtitleView.setVisibility(View.GONE);
//                    // mSubtitleView.destroy();
//                    // mSubtitleView.clearSubtitleCache();
//                    // mSubtitleView.isInternal = false;
//                    hideBottom();
//                    Toast.makeText(getContext(), HomeActivity.getRes().getString(R.string.vod_sub_off), Toast.LENGTH_SHORT).show();
//                }
                return true;
            }
        });
    }

    /**
     * --显示迷你屏显示按钮----------------------------------------------------------------------------
     */
    private void setupViewScreenDisplay() {
        mTopRoot2.setVisibility(Hawk.get(HawkConfig.SCREEN_DISPLAY, GONE));
        mScreenDisplay.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                toggleMiniScreenDisplay();
            }
        });
    }

    /**
     * --根布局----------------------------------------------------------------------------
     */
    private void setupViewRootView() {
        View rootView = findViewById(R.id.rootView);
        if (rootView == null) {
            return;
        }
        //#检查处理屏幕锁屏
        rootView.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (mIsLocked) {
                    if (event.getAction() == MotionEvent.ACTION_UP) {
                        if (mLockView.getVisibility() == View.VISIBLE) {
                            mLockView.setVisibility(GONE);
                        } else {
                            showLockView();
                        }
                    }
                }
                return mIsLocked;
            }
        });
    }

    /**
     * 设置屏显开关
     */
    private void setupViewVodLock() {
        //-- button : 屏幕锁 lock screen ----------------------------------------
        if (mLockView == null) {
            Logger.e("mLockView is null, setupViewVodLock returns"); // 添加日志记录
            return;
        }
        mLockView.setOnClickListener(v -> {
            this.mIsLocked = !mIsLocked;
            mLockView.setImageResource(mIsLocked ? R.drawable.icon_lock : R.drawable.icon_unlock);
            Handler handler = getHandler();
            if (handler != null) {
                if (mIsLocked) {
                    Message obtain = Message.obtain();
                    obtain.what = 1003; //隐藏底部菜单
                    handler.sendMessage(obtain);
                }else {
                    Message obtain = Message.obtain();
                    obtain.what = 1002; //显示底部菜单
                    handler.sendMessage(obtain);
                }
            }
            showLockView();
        });
    }

    @Override
    public Handler getHandler() {
        return mHandler;
    }

    private void setupViewTimeStepPlay() {
        if (mPlayerTimeStepBtn == null) {
            return;
        }
        mPlayerTimeStepBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                int step = Hawk.get(HawkConfig.PLAY_TIME_STEP, 5);
                step += 5;
                if (step > 30) {
                    step = 5;
                }
                Hawk.put(HawkConfig.PLAY_TIME_STEP, step);
                updatePlayerCfgView();
            }
        });
    }

    /**
     * 播放结束时间（多少秒前结束播放）
     */
    private void setupViewTimeSkipPlay() {
        if (mPlayerTimeSkipBtn == null) {
            return;
        }
        mPlayerTimeSkipBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    int step = Hawk.get(HawkConfig.PLAY_TIME_STEP, 5);
                    int et = mPlayerConfig.getInt("et");
                    et += step;
                    if (et > 60 * 10) et = 0;
                    mPlayerConfig.put("et", et);
                    updatePlayerCfgView();
                    mListener.updatePlayerCfg();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 播放开始时间（多少秒后开始播放）
     */
    private void setupViewTimeStartPlay() {
        mPlayerTimeStartBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    int step = Hawk.get(HawkConfig.PLAY_TIME_STEP, 5);
                    int st = mPlayerConfig.getInt("st");
                    st += step;
                    if (st > 60 * 10) st = 0;
                    mPlayerConfig.put("st", st);
                    updatePlayerCfgView();
                    mListener.updatePlayerCfg();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void setupViewPlayerIJKPlay() {
        mPlayerIJKBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    String ijk = mPlayerConfig.getString("ijk");
                    mPlayerConfig.put("ijk", ijk);
                    updatePlayerCfgView();
                    mListener.updatePlayerCfg();
                    mListener.replay();//重置播放
                    hideBottom();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 播放方式切换
     */
    private void setupViewPlayerPlay() {
        //-- 播放模式----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
        if (mPlayerView == null) {
            return;
        }
        mPlayerView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                FastClickCheckUtil.check(view);
                togglePlayer();
            }
        });
    }

    public void togglePlayer() {
        //显示一个弹窗用户选择
        try {
            int playerType = mPlayerConfig.optInt("pl", 0);
            int defaultPos = 0;
            List<Integer> players = new ArrayList<>();
            players.add(0);  // System
            players.add(1);  // IJK
            players.add(2);  // Exo
            players.add(3);  // Ali
            if (mxPlayerExist) {
                players.add(10);
            }
            if (reexPlayerExist) {
                players.add(11);
            }
            if (KodiExist) {
                players.add(12);
            }
            //显示一个选择框，

            SelectDialog<Integer> dialog = new SelectDialog<>(mActivity);
            dialog.setTip("R.string.dia_player");
            dialog.setAdapter(new SelectDialogAdapter.SelectDialogInterface<Integer>() {
                @Override
                public void click(Integer value, int pos) {
                    dialog.cancel();
                    int thisPlayType = players.get(pos);
                    try {
                        mPlayerConfig.put("pl", thisPlayType);
                    } catch (JSONException e) {
                        throw new RuntimeException(e);
                    }
                    updatePlayerCfgView();
                    mListener.updatePlayerCfg();
                    mListener.replay();
                    setPlayer(true);
                }

                @Override
                public String getDisplay(Integer val) {
                    return PlayerHelper.getPlayerName(val);
                }
            }, new DiffUtil.ItemCallback<Integer>() {
                @Override
                public boolean areItemsTheSame(@NonNull Integer oldItem, @NonNull Integer newItem) {
                    return oldItem.intValue() == newItem.intValue();
                }

                @Override
                public boolean areContentsTheSame(@NonNull Integer oldItem, @NonNull Integer newItem) {
                    return oldItem.intValue() == newItem.intValue();
                }
            }, players, defaultPos);

            dialog.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void setPlayer(boolean reset) {

    }

    /**
     * 播放屏幕比例
     */
    private void setupViewScalePlay() {
        // --- 缩放模式 -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
        View view = mPlayerScaleView;
        if (view == null) {
            return;
        }
        view.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                toggleScreenScale();
            }
        });

        view.setOnLongClickListener(new OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                toggleOrientation();
                return true;
            }
        });
    }

    /**
     * 变更播放比例
     */
    public void toggleScreenScale() {
        try {
            int scaleType = mPlayerConfig.optInt("sc", 0);
            scaleType++;
            if (scaleType > 5) scaleType = 0;
            mPlayerConfig.putOpt("sc", scaleType);
            updatePlayerCfgView();
            mListener.updatePlayerCfg();
            mControlWrapper.setScreenScaleType(scaleType);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置上一集
     */
    private void setupViewPrevPlay() {
        // == 播放 上一集，上一个----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
        mPrevBtn.setOnClickListener(view -> {
            mListener.playPrev();
            hideBottom();
        });
    }

    /**
     * --设置下一集----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
     */
    private void setupViewNextPlay() {
        // --播放 下一集 下一个--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
        mNextBtn.setOnClickListener(view -> {
            mListener.playNext(false);
            hideBottom();
        });
    }

    /**
     * --播放 刷新 重播--------
     */
    private void setupViewRetryPlay() {
        // --播放 刷新 重播--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
        if (mPlayerRetry == null) {
            return;
        }
        mPlayerRetry.setOnClickListener(v -> {
            mListener.replay();
            hideBottom();
        });

        mPlayerRetry.setOnLongClickListener(new OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                mListener.replay();
                hideBottom();
                return true;
            }
        });
    }

    /**
     * 设置播放进度
     */
    private void setupViewSeekBar() {
        // --播放 进度条--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
        mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (!fromUser) {
                    return;
                }

                long duration = mControlWrapper.getDuration();
                long newPosition = (duration * progress) / seekBar.getMax();
                if (mCurrentTime != null) mCurrentTime.setText(stringForTime((int) newPosition));
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                mIsDragging = true;
                mControlWrapper.stopProgress();
                mControlWrapper.stopFadeOut();
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                long duration = mControlWrapper.getDuration();
                long newPosition = (duration * seekBar.getProgress()) / seekBar.getMax();
                mControlWrapper.seekTo((int) newPosition);
                mIsDragging = false;
                mControlWrapper.startProgress();
                mControlWrapper.startFadeOut();
            }
        });
    }

    /**
     * 设置快进按钮
     */
    private void setupViewFFwdBtn() {
        // --快进按钮--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
        View view = mPlayerSpeedView;
        if (view == null) {
            return;
        }
        // 点击
        view.setOnClickListener(view1 -> {
            //点击之后隐藏底部栏
            hideBottom(8000);
            togglePlaySpeed();
        });
        //长按
        view.setOnLongClickListener(new OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                float currentSpeed = mControlWrapper.getSpeed();
                if (currentSpeed == 1.0f) {
                    setSpeed(5.0f);
                } else {
                    setSpeed(1.0f);
                }
                return true;
            }
        });
    }

    /**
     * 变更播放速度（)
     */
    public void togglePlaySpeed() {
        if (!isPlaying() || !canAdjustSpeed()) return;
        addSpeed();
    }

    public boolean isPlaying() {
        return mControlWrapper.isPlaying();
    }

    public boolean canAdjustSpeed() {
        return true;
    }

    private void setupViewPlayPause() {
        //== 播放/暂停 ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
        View view = mPauseBtn;

        if (view == null) {
            return;
        }
        view.setOnClickListener(view1 -> {
            togglePlay();
            if (!isPaused) {
                hideBottom();
            }
        });
    }

    private void toggleLockViewVisibility() {
        if (mLockView == null) {
            // 假设showLockView是一个将mLockView显示出来的方法
            showLockView();
        } else if (mLockView.getVisibility() == View.VISIBLE) {
            mLockView.setVisibility(View.GONE);
        } else {
            // 如果是GONE或INVISIBLE状态，显示它
            mLockView.setVisibility(View.VISIBLE);
        }
    }

    private void toggleMiniScreenDisplay() {
        mTopRoot2.setVisibility(mTopRoot2.getVisibility() == VISIBLE ? GONE : VISIBLE);
        Hawk.put(HawkConfig.SCREEN_DISPLAY, mTopRoot2.getVisibility());
        hideBottom();
        //Toast.makeText(getContext(), "点击显示网速 播放进度 时间", Toast.LENGTH_SHORT).show();
    }

    /**
     * 变更横竖屏
     */
    private void toggleOrientation() {
        int checkOrientation = mActivity.getRequestedOrientation();
        if (checkOrientation == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE || checkOrientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE || checkOrientation == ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE) {
            mActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
        } else if (checkOrientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT || checkOrientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT || checkOrientation == ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT) {
            mActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
        }

    }

    /**
     * 设置播放速度
     *
     * @param speed 播放速度
     */
    public String setSpeed(float speed) {
        mControlWrapper.setSpeed(speed);
        updatePlayerCfgView();
        mListener.updatePlayerCfg();
        return setSpeedText(getSpeedText());
    }

    public String addSpeed() {
        float speed = getSpeed();
        float addon = speed >= 2 ? 1f : 0.25f;
        speed = speed >= 5 ? 0.25f : Math.min(speed + addon, 5.0f);
        return setSpeed(speed);
    }

    public String addSpeed(float value) {
        float speed = getSpeed();
        speed = Math.min(speed + value, 5);
        return setSpeed(speed);
    }

    public String subSpeed() {
        return subSpeed(0.25F);
    }

    public String subSpeed(float value) {
        float speed = getSpeed();
        speed = Math.max(speed - value, 0.2f);
        return setSpeed(speed);
    }

    private String setSpeedText(String text) {
        if (mPlayerSpeedText instanceof TextView) {
            text = "x".concat(text);
            ((TextView) mPlayerSpeedText).setText(text);
        }
        return text;
    }

    private String getSpeedText() {
        return String.format(Locale.getDefault(), "%.2f", getSpeed());
    }

    public float getSpeed() {
        return mControlWrapper.getSpeed();
    }

    private void showLockView() {
        mLockView.setVisibility(VISIBLE);
        mHandler.removeCallbacks(mLockRunnable);
        mHandler.postDelayed(mLockRunnable, 3000);
    }

    public void showParse(boolean userJxList) {
        mParseRoot.setVisibility(userJxList ? VISIBLE : GONE);
    }

    private JSONObject mPlayerConfig = null;

    private boolean mxPlayerExist = false;

    private boolean reexPlayerExist = false;
    private boolean KodiExist = false;

    public void setPlayerConfig(JSONObject playerCfg) {
        this.mPlayerConfig = playerCfg;
        updatePlayerCfgView();
        //其他播放器
        mxPlayerExist = MXPlayer.getPackageInfo() != null;
        reexPlayerExist = ReexPlayer.getPackageInfo() != null;
//        KodiExist = Kodi.getPackageInfo() != null;
    }

    /**
     * 更新播放配置UI
     */
    void updatePlayerCfgView() {
        try {
            int playerType = mPlayerConfig.optInt("pl", 0);
            if (mPlayerTextBtn instanceof TextView) {
                ((TextView) mPlayerTextBtn).setText(PlayerHelper.getPlayerName(playerType));
            }
            if (mPlayerScaleTxt instanceof TextView) {
                ((TextView) mPlayerScaleTxt).setText(PlayerHelper.getScaleName(mPlayerConfig.optInt("sc", 0)));
            }

            mPlayerIJKBtn.setText(mPlayerConfig.optString("ijk"));
            mPlayerIJKBtn.setVisibility(playerType == 1 ? VISIBLE : GONE);

            mPlayerTimeStartBtn.setText(PlayerUtils.stringForTime(mPlayerConfig.optInt("st") * 1000));
            mPlayerTimeSkipBtn.setText(PlayerUtils.stringForTime(mPlayerConfig.optInt("et") * 1000));
            mPlayerTimeStepBtn.setText(Hawk.get(HawkConfig.PLAY_TIME_STEP, 5) + "s");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void setTitle(String playTitleInfo) {
        if (mPlayTitle != null) {
            mPlayTitle.setText(playTitleInfo);
        }
    }

    public void resetSpeed() {
        skipEnd = true;
        mHandler.removeMessages(1004);
        mHandler.sendEmptyMessageDelayed(1004, 100);
    }


    /**
     * @param mListener
     */
    public void setVodListener(VodControlListener mListener) {
        this.mListener = mListener;
    }

    private VodControlListener mListener;

    private boolean skipEnd = true;

    @Override
    protected void setProgress(int duration, int position) {
        if (mIsDragging) {
            return;
        }
        super.setProgress(duration, position);
        //跳转(播放完毕)
        if (skipEnd && position != 0 && duration != 0) {
            int et = mPlayerConfig.optInt("et", 0);
            if (et > 0 && position + (et * 1000) >= duration) {
                skipEnd = false;
                mListener.playNext(true);
            }
        }
        //显示估计的结束时间
        // takagen99 : Calculate finish time
        CalculateFinishTime();

        mCurrentTime.setText(PlayerUtils.stringForTime(position));
        mTotalTime.setText(PlayerUtils.stringForTime(duration));
        seekTime.setText((PlayerUtils.stringForTime(position)) + " | " + (PlayerUtils.stringForTime(duration))); //右上角进度条时间显示

        if (duration > 0) {
            mSeekBar.setEnabled(true);
            int pos = (int) (position * 1.0 / duration * mSeekBar.getMax());
            mSeekBar.setProgress(pos);
        } else {
            mSeekBar.setEnabled(false);
        }
        int percent = mControlWrapper.getBufferedPercentage();
        if (percent >= 95) {
            mSeekBar.setSecondaryProgress(mSeekBar.getMax());
        } else {
            mSeekBar.setSecondaryProgress(percent * 10);
        }
    }

    private void CalculateFinishTime() {
        long TimeRemaining = mControlWrapper.getDuration() - mControlWrapper.getCurrentPosition();
        Calendar date = Calendar.getInstance();
        long t = date.getTimeInMillis();
        Date afterAdd = new Date(t + TimeRemaining);
        SimpleDateFormat timeEnd = new SimpleDateFormat("hh:mm aa", Locale.ENGLISH);

        if (isPaused) {
            mTimeEnd.setText(getContext().getString(R.string.vod_remaining_time)
                    + " "
                    + PlayerUtils.stringForTime((int) TimeRemaining)
                    + " | "
                    + getContext().getString(R.string.vod_ends_at)
                    + " " + timeEnd.format(afterAdd));
        } else {
            mTimeEnd.setText(getContext().getString(R.string.vod_ends_at)
                    + " "
                    + timeEnd.format(afterAdd));
        }
    }

    private boolean simSlideStart = false;

    private int simSeekPosition = 0;
    private long simSlideOffset = 0;

    public void tvSlideStop() {
        if (!simSlideStart) return;
        mControlWrapper.seekTo(simSeekPosition);
        if (!mControlWrapper.isPlaying()) mControlWrapper.start();
        simSlideStart = false;
        simSeekPosition = 0;
        simSlideOffset = 0;
    }

    private boolean isLockScreen() {
        return mIsLocked;
    }

    public void tvSlideStart(int dir) {
        int duration = (int) mControlWrapper.getDuration();
        if (duration <= 0) return;
        if (!simSlideStart) {
            simSlideStart = true;
        }
        // 每次10秒
        simSlideOffset += (10000.0f * dir);
        int currentPosition = (int) mControlWrapper.getCurrentPosition();
        int position = (int) (simSlideOffset + currentPosition);
        if (position > duration) position = duration;
        if (position < 0) position = 0;
        updateSeekUI(currentPosition, position, duration);
        simSeekPosition = position;
    }

    @Override
    protected void updateSeekUI(int curr, int seekTo, int duration) {
        super.updateSeekUI(curr, seekTo, duration);
        if (seekTo > curr) {
            mProgressIcon.setImageResource(R.drawable.icon_pre);
        } else {
            mProgressIcon.setImageResource(R.drawable.icon_back);
        }
        mProgressText.setText(PlayerUtils.stringForTime(seekTo) + " / " + PlayerUtils.stringForTime(duration));
        mHandler.sendEmptyMessage(1000);
        mHandler.removeMessages(1001);
        mHandler.sendEmptyMessageDelayed(1001, 1000);
    }

    @Override
    protected void onPlayStateChanged(int playState) {
        //-- 播放状态回调 ----------------------------------
        super.onPlayStateChanged(playState);
        switch (playState) {
            case VideoView.STATE_IDLE:
                break;
            case VideoView.STATE_PLAYING:
                isPaused = false;
                mPauseImg.setImageDrawable(getResources().getDrawable(R.drawable.v_pause));
                startProgress();
                break;
            case VideoView.STATE_PAUSED:
                isPaused = true;
                mPauseImg.setImageDrawable(getResources().getDrawable(R.drawable.v_play));
                break;
            case VideoView.STATE_ERROR:
                mListener.errReplay();
                break;
            case VideoView.STATE_PREPARED:
            case VideoView.STATE_BUFFERED:
                break;
            case VideoView.STATE_PREPARING:
            case VideoView.STATE_BUFFERING:
                break;
            case VideoView.STATE_PLAYBACK_COMPLETED:
                mListener.playNext(true);
                break;
        }
    }

    boolean isBottomVisible() {
        return mBottomRoot.getVisibility() == VISIBLE;
    }

    void showBottom() {

        mHandler.removeMessages(1003);
        mHandler.sendEmptyMessage(1002);
        mHandler.post(mTimeRunnable);
        mHandler.postDelayed(mHideBottomRunnable, 8000);
    }
    //runnable Task-----------

    private final Runnable mUpdateLayout = new Runnable() {
        @Override
        public void run() {
            mBottomRoot.requestLayout();
        }
    };
    Runnable mHideBottomRunnable = new Runnable() {
        @Override
        public void run() {
            hideBottom();
        }
    };
    private final Runnable mLockRunnable = new Runnable() {
        @Override
        public void run() {
            mLockView.setVisibility(GONE);
        }
    };


    // takagen99 : To get system time
    private final Runnable mTimeRunnable = new Runnable() {
        @Override
        public void run() {
            Date date = new Date();
            SimpleDateFormat timeFormat = new SimpleDateFormat("hh:mm aa", Locale.ENGLISH);
            mPlayPauseTime.setText(timeFormat.format(date));
            mTime.setText(timeFormat.format(date));
            mHandler.postDelayed(this, 1000);
        }
    };
    // Runnable Task========

    void hideBottom() {
        mHandler.removeMessages(1002);
        mHandler.sendEmptyMessage(1003);
        mHandler.removeCallbacks(mHideBottomRunnable);
    }

    private void hideBottom(long delayMillis) {
        mHandler.removeCallbacks(mHideBottomRunnable);
        mHandler.postDelayed(mHideBottomRunnable, delayMillis);
    }

    private void hideControl() {
        hideControl(true);
    }

    private void hideControl(boolean hideInfo) {

    }

    public boolean isBackground() {
        return false;
    }

    @Override
    public boolean onKeyEvent(KeyEvent event) {
        if (super.onKeyEvent(event)) {
            return true;
        }
        if (isBottomVisible()) {
            hideBottom(8000);
            return super.dispatchKeyEvent(event);
        }

        boolean isInPlayback = isInPlaybackState();
        int keyCode = event.getKeyCode();
        int action = event.getAction();

        if (action == KeyEvent.ACTION_DOWN) {
            if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT || keyCode == KeyEvent.KEYCODE_DPAD_LEFT) {
                if (isInPlayback) {
                    tvSlideStart(keyCode == KeyEvent.KEYCODE_DPAD_RIGHT ? 1 : -1);
                    return true;
                }
            } else if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER || keyCode == KeyEvent.KEYCODE_ENTER || keyCode == KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE) {
                if (isInPlayback) {
                    togglePlay();
                    if (!isBottomVisible() && isPaused) {
                        showBottom();
                    }
                    return true;
                }
                // takagen99 : Key Up to focus Start Time Skip
            } else if (keyCode == KeyEvent.KEYCODE_DPAD_UP) {
                if (!isBottomVisible()) {
                    showBottom();
                    isKeyUp = true;
                    return true;
                }
            } else if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN) {
                if (!isBottomVisible()) {
                    showBottom();
                    return true;
                }
            }
        } else if (action == KeyEvent.ACTION_UP) {
            if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT || keyCode == KeyEvent.KEYCODE_DPAD_LEFT) {
                if (isInPlayback) {
                    tvSlideStop();
                    return true;
                }
            }
        }
        return super.dispatchKeyEvent(event);
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        int keyCode = event.getKeyCode();
        if (isBottomVisible() && mPlayerSpeedView.isFocused()) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                if (keyCode == KeyEvent.KEYCODE_DPAD_UP) {
                    try {
                        addSpeed();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN) {
                    try {
                        subSpeed();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        } else if (isBottomVisible() && mPlayerTimeStartBtn.isFocused()) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                if (keyCode == KeyEvent.KEYCODE_DPAD_UP) {
                    increaseTime("st");
                } else if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN) {
                    decreaseTime("st");
                }
            }
        } else if (isBottomVisible() && mPlayerTimeSkipBtn.isFocused()) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                if (keyCode == KeyEvent.KEYCODE_DPAD_UP) {
                    increaseTime("et");
                } else if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN) {
                    decreaseTime("et");
                }
            }
        }
        return super.dispatchKeyEvent(event);
    }

    @Override
    public boolean onSingleTapConfirmed(MotionEvent e) {
        if (!isBottomVisible()) {
            showBottom();
        } else {
            hideBottom();
        }
        return true;
    }

    // takagen99 : On release long press, resume previous speed
    @Override
    public boolean onTouchEvent(MotionEvent e) {
        if (e.getAction() == MotionEvent.ACTION_UP) {
            if (fromLongPress) {
                // Set back to Pause Icon
                mProgressTop.setVisibility(GONE);
                if (mPauseIcon instanceof ImageView) {
                    ((ImageView) mPauseIcon).setImageResource(R.drawable.play_pause);
                }
                // Set back to current speed
                mSpeed = currentSpeed;
                setSpeed(mSpeed);
                fromLongPress = false;
            }
        }
        return super.onTouchEvent(e);
    }

    @Override
    public void onLongPress(MotionEvent e) {
        //处理长按事件-快进播放
        if (!isPaused) {
            fromLongPress = true;
            try {
                currentSpeed = (float) getSpeed();
                circularReveal(mTapSeek, 1);
                // Set Fast Forward Icon
                mProgressTop.setVisibility(VISIBLE);
                if (mPauseIcon instanceof ImageView) {
                    ((ImageView) mPauseIcon).setImageResource(R.drawable.play_ffwd);
                }
                // Set x3 Speed only if less than x3
                if (currentSpeed < 3.0f) {
                    mSpeed = 3.0f;
                } else {
                    mSpeed = currentSpeed;
                }
                setSpeed(mSpeed);
            } catch (Exception f) {
                f.printStackTrace();
            }
        }
    }

    private int tapDirection;

    // takagen99 : Added double tap to rewind or fast forward with animation
    @Override
    public boolean onDoubleTap(MotionEvent e) {
        int threeScreen = PlayerUtils.getScreenWidth(getContext(), true) / 3;

        if (e.getX() > 0 && e.getX() < threeScreen) {
            // left side <<<<<
            tapDirection = -1;
        } else if ((e.getX() > threeScreen) && (e.getX() < (threeScreen * 2))) {
            // middle screen
            tapDirection = 0;
        } else if (e.getX() > (threeScreen * 2)) {
            // right side >>>>>
            tapDirection = 1;
        }
        if (tapDirection == 0 || isPaused) {
            togglePlay();
        } else {
            circularReveal(mTapSeek, tapDirection);
            int duration = (int) mControlWrapper.getDuration();
            int currentPosition = (int) mControlWrapper.getCurrentPosition();
            // Fast Forward or Backward by 10 seconds
            int position = (int) (10000.0f * tapDirection) + currentPosition;
            if (position > duration) position = duration;
            if (position < 0) position = 0;
            updateSeekUI(currentPosition, position, duration);
            mControlWrapper.seekTo(position);
        }
        return true;
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public static void circularReveal(View v, int direction) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            int radius = Math.max(v.getWidth(), v.getHeight()) / 2;
            int width = 0;
            if (direction == 1) {
                width = v.getWidth();
            }
            TransitionManager.beginDelayedTransition((ViewGroup) v);
            Animator anim = ViewAnimationUtils.createCircularReveal(v, width, v.getHeight() / 2, 0, radius);
            anim.addListener(new Animator.AnimatorListener() {
                @Override
                public void onAnimationStart(Animator animation) {
                    v.setVisibility(VISIBLE);
                }

                @Override
                public void onAnimationEnd(Animator animation) {
                    v.setVisibility(GONE);
                }

                @Override
                public void onAnimationCancel(Animator animation) {

                }

                @Override
                public void onAnimationRepeat(Animator animation) {

                }
            });
            anim.setDuration(600);
            anim.start();
        }
    }

    void increaseTime(String type) {
        try {
            int step = Hawk.get(HawkConfig.PLAY_TIME_STEP, 5);
            int time = mPlayerConfig.getInt(type);
            time += step;
            if (time > 30 * 10) time = 0;          // 600 = 10 mins
            mPlayerConfig.put(type, time);

//            // takagen99: Reference FongMi to get exact opening skip time
//            int current = (int) mControlWrapper.getCurrentPosition();
//            int duration = (int) mControlWrapper.getDuration();
//            if (current > duration / 2) return;
//            mPlayerConfig.put("st", current / 1000);

            updatePlayerCfgView();
            mListener.updatePlayerCfg();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    void decreaseTime(String type) {
        try {
            int step = Hawk.get(HawkConfig.PLAY_TIME_STEP, 5);
            int time = mPlayerConfig.getInt(type);
            time -= step;
            if (time < 0) time = (30 * 10);
            mPlayerConfig.put(type, time);

            updatePlayerCfgView();
            mListener.updatePlayerCfg();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean onBackPressed() {
        if (super.onBackPressed()) {
            return true;
        }
        //隐去底部栏
        if (isBottomVisible()) {
            hideBottom();
            return true;
        }
        //如果被锁定，显示锁
        if (isLockScreen()) {
            if (mLockView.getVisibility() == View.VISIBLE) {
                mLockView.setVisibility(GONE);
                Toast.makeText(getContext(), "请先打开屏锁", Toast.LENGTH_LONG).show();
            } else {
                showLockView();
            }
            return true;
        }

        // 转屏
        int checkOrientation = mActivity.getRequestedOrientation();
        if (checkOrientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT || checkOrientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT || checkOrientation == ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT) {
            mActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
        }
        //退出播放

        return false;
    }

}
